﻿package com.zhuangyzh.cmpp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 启动一个线程去接收和发送数据，如果队列处理完毕就关闭线程
 */
public class CMPPSender {
    private List<byte[]> sendData = new ArrayList<byte[]>();// 需要发出的二进制数据队列
    private List<byte[]> getData = new ArrayList<byte[]>();// 需要接受的二进制队列
    private DataOutputStream out;
    private DataInputStream in;

    public CMPPSender(DataOutputStream out, DataInputStream in,
            List<byte[]> sendData) {
        super();
        this.sendData = sendData;
        this.out = out;
        this.in = in;
    }

    public int start() throws Exception {
        if (out != null && null != sendData) {
            for (byte[] data : sendData) {
                sendMsg(data);
                byte[] returnData = getInData();
                if (null != returnData) {
                    getData.add(returnData);
                    // CMPPContainer.addISMGMessage(returnData);
                }
            }
        }
        if (in != null && null != getData) {
            for (byte[] data : getData) {
                if (data.length >= 8) {
                    CMPPHeader head = new CMPPHeader(data);
                    switch (head.getCommand_Id()) {
                    case CMPPDefine.CMPP_CONNECT_RESP:
                        CMPPConnectResp connectResp = new CMPPConnectResp(data);
                        // System.out.println(new
                        // SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new
                        // Date())+"链接短信网关,状态:"+connectResp.getStatusStr()+" 序列号："+connectResp.getSequence_Id());
                        return connectResp.getStatus();
                    case CMPPDefine.CMPP_SUBMIT_RESP:
                        CMPPSubmitResp submitResp = new CMPPSubmitResp(data);
                        // System.out.println("数据于"+new
                        // SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new
                        // Date())+"向用户下发短信，状态码:"+submitResp.getResult()+" 序列号："+submitResp.getSequence_Id());
                        return submitResp.getResult();
                    case CMPPDefine.CMPP_ACTIVE_TEST:
                        CMPPActiveTestResp activeResp = new CMPPActiveTestResp(data);
                        CMPPContainer.sendActiveTestResp(activeResp);
                        return 0;
                        // logger.info(new
                        // SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new
                        // Date())+"短信网关与短信网关进行连接检查"+" 序列号："+activeResp.getSequenceId());
                    case CMPPDefine.CMPP_ACTIVE_TEST_RESP:
                        System.out.println("收到 CMPP_ACTIVE_TEST_RESP 序号:"
                                + head.getSequence_Id());
                        return 0;
                    default:
                        System.out.println("无法解析IMSP返回的包结构：包长度为"
                                + head.getTotal_Length());
                        System.out.println("无法解析IMSP返回的包结构：消息ID为"
                                + head.getCommand_Id());
                        System.out.println("data:" + data);
                        break;
                    }
                }
            }
        }
        return -1;
    }

    public List<byte[]> getGetData() {
        return getData;
    }

    /**
     * 在本连结上发送已打包后的消息的字节
     * 
     * @param data
     *            :要发送消息的字节
     */
    private boolean sendMsg(byte[] data) throws Exception {
        try {
            out.write(data);
            out.flush();
            return true;
        } catch (NullPointerException ef) {
            System.out.println("在本连结上发送已打包后的消息的字节:无字节输入");
        }
        return false;
    }

    private byte[] getInData() throws IOException {
        try {
            int len = in.readInt();
            if (null != in && 0 != len) {
                byte[] data = new byte[len - 4];
                in.read(data);
                return data;
            } else {
                return null;
            }
        } catch (NullPointerException ef) {
            System.out.println("在本连结上接受字节消息:无流输入");
            return null;
        } catch (EOFException eof) {
            System.out.println("在本连结上接受字节消息:" + eof.getMessage());
            return null;
        }
    }

}